<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input placeholder="SPU名称" v-model="spuForm.spuName"></el-input>
    </el-form-item>

    <el-form-item label="品牌">
      <el-select v-model="spuForm.tmId" placeholder="请选择">
        <el-option
          v-for="tm in tmList"
          :key="tm.id"
          :value="(tm.id as number)"
          :label="tm.tmName"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="SPU描述">
      <el-input v-model="spuForm.description" type="textarea" placeholder="SPU描述" :rows="3"></el-input>
    </el-form-item>

    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="(spuImageList as any)"
        :action="action"
        list-type="picture-card"
        :on-success="handleSuccess"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <div class="mb-10">
        <el-select v-model="attrIdName" placeholder="请选择" class="mr-10">
          <el-option
            v-for="saleAttr in saleAttrList"
            :key="saleAttr.id"
            :value="`${ saleAttr.id }:${ saleAttr.name }`"
            :label="saleAttr.name"
          ></el-option>
        </el-select>
        <el-button type="primary" @click="addSpuSaleAttr">添加销售属性</el-button>
      </div>
      <el-table :data="spuForm.spuSaleAttrList" border>
        <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
        <el-table-column label="属性名" prop="saleAttrName" width="200"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template #default="{ row, $index }">
          
            <el-tag
              v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
              :key="index"
              class="mr-5"
              closable
              :disable-transitions="false"
              @close="handleClose(index, row.spuSaleAttrValueList)"
            >
              {{ saleAttrValue.saleAttrValueName }}
            </el-tag>


            <el-input
              v-if="row.inputVisible"
              v-model="row.inputValue"
              ref="InputRef"
              size="small"
              style="width: 100px;"
              @blur="handleInputConfirm(row)"
            />
            <el-button v-else size="small" @click="showInput(row)">新增</el-button>
          
          
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ row, $index }">
            <el-button type="danger" :icon="Delete" size="small" @click="deleteSpuSaleAttr($index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSave">保存</el-button>
      <el-button @click="cancelSave">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { STATUS } from '../../index.vue'
import { ref, onMounted, computed, nextTick } from 'vue'
import { ElMessage, type UploadProps,} from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import trademarkApi, { type TrademarkModel } from '@/api/trademark'
import spuApi, { type SaleAttrModel, type SpuModel, type SpuImageModel, type SpuSaleAttrModel, type SpuSaleAttrValueModel } from '@/api/spu'
import useCategoryStore from '@/stores/category'
import { cloneDeep } from 'lodash'
const categoryStore = useCategoryStore()
const action = `${ import.meta.env.VITE_API_URL }/admin/product/upload`
const emits = defineEmits<{
  (e: 'update:modelValue', status: number): void,
  (e: 'spuInfo'): void
}>()
const props = defineProps<{
  spuInfo: SpuModel
}>()

// 取消保存
const cancelSave = () => {
  emits('update:modelValue', STATUS.SPULIST)
  emits('spuInfo')
}
// 保存
const onSave = async () => {
  // 组装数据
  // 组装三级分类数据
  spuForm.value.category3Id = categoryStore.category3Id
  // 收集图片数据
  let tempSpuImageList: SpuImageModel[] = spuImageList.value.map(item => {
    return {
      imgName: item.name!,
      imgUrl: item.id ? item.imgUrl : item.response.data // 接口返回的图片有id和imgUrl,新增的图片没有id但是有response
    }
  })
  spuForm.value.spuImageList = tempSpuImageList;
  // 删除掉销售属性中的inputVisible和inputValue
  spuForm.value.spuSaleAttrList.forEach(item => {
    delete item.inputValue
    delete item.inputVisible
  })

  // 数据简单校验
  const { category3Id, spuName, description, tmId, spuSaleAttrList, spuImageList: spuImageList2 } = spuForm.value
  if ( !(category3Id && spuName && description && tmId && spuSaleAttrList.length && spuImageList2.length) ) {
    ElMessage.error('请填写完整表单数据')
    return
  }

  // 发送请求
  try {
    if (spuForm.value.id) { // 编辑保存
      await spuApi.updateSpu(spuForm.value)
    } else { // 新增保存
      await spuApi.saveSpu(spuForm.value)
    }
    ElMessage.success('保存成功')
    emits('update:modelValue', STATUS.SPULIST) // 切换界面
    emits('spuInfo') // 清空父组件中spuInfo的数据
  } catch (error) {
    console.error(error)
    ElMessage.error('保存失败,请重试')
  }
}





// 销售属性收集
const attrIdName = ref("")
// 表格添加销售属性
const addSpuSaleAttr = () => {
  if (!attrIdName.value) {
    return
  }
  // console.log(attrIdName.value)  // '1:颜色'
  //        "1"            "颜色"
  const [baseSaleAttrId, saleAttrName] = attrIdName.value.split(':');

  // spuForm.value.spuSaleAttrList 表格要展示数据已经有了
  spuForm.value.spuSaleAttrList.push({
    baseSaleAttrId: Number(baseSaleAttrId),
    saleAttrName,
    spuSaleAttrValueList: [
      //  销售属性值先写死,循环展示用,一会过来清空即可
      // {
      //   "baseSaleAttrId": 1,
      //   "saleAttrValueName": "red"
      // },
      // {
      //   "baseSaleAttrId": 1,
      //   "saleAttrValueName": "blue"
      // }
    ], // 销售属性值列表
    inputVisible: false, // 有几行数据,就应该有几个布尔值来控制input的显示和隐藏
    inputValue: "" // 作为这一行需要收集的数据
  })

  // 把绑定在下拉框中的数据清空掉
  attrIdName.value = ""
}
// 表格删除销售属性
const deleteSpuSaleAttr = (index: number) => {
  spuForm.value.spuSaleAttrList.splice(index, 1)
}




const InputRef = ref<HTMLInputElement>()
// 添加销售属性值
const handleInputConfirm = (row: SpuSaleAttrModel) => {
  row.inputVisible = false; // input隐藏

  // 非空校验
  if (!row.inputValue?.trim()) {
    return
  }

  // 重复校验
  let isRepeat = row.spuSaleAttrValueList.some(item => item.saleAttrValueName == row.inputValue)
  if (isRepeat) {
    ElMessage.error('输入的内容重复,请重试')
    row.inputValue = "" // 添加过之后就把收集的数据清空掉
    return
  }

  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.inputValue.trim()!
  })

  row.inputValue = "" // 添加过之后就把收集的数据清空掉
}

// 展示当前属性值行的input(新增按钮)
const showInput = (row: SpuSaleAttrModel) => {
  row.inputVisible = true

  nextTick(() => {
    InputRef.value?.focus()
  })
}

// 删除销售属性值
const handleClose = (index: number, spuSaleAttrValueList: SpuSaleAttrValueModel[]) => {
  spuSaleAttrValueList.splice(index, 1)
}







// 关于照片墙
const spuImageList = ref<SpuImageModel[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// 上传成功的回调
const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
  spuImageList.value = uploadFiles as any
}
// 删除图片回调
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log('删除的回调', uploadFile, uploadFiles)
  spuImageList.value = uploadFiles as any
}
// 预览回调
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  // console.log(uploadFile)
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}



// 准备数据 - 收集数据
const initSpuForm = (): SpuModel => ({
  category3Id: undefined, // 这个数据在发请求之前组装,现在先不动
  spuName: '',
  description: '',
  tmId: undefined,
  spuSaleAttrList: [],
  spuImageList: []
})
const spuForm = ref<SpuModel>(initSpuForm())




// 获取品牌下拉方法
const tmList = ref<TrademarkModel[]>([])
const getTrademarkList = async () => {
  try {
    let result = await trademarkApi.getTrademarkList()
    tmList.value = result
  } catch (error) {
    console.log(error)
    ElMessage.error('获取品牌下拉失败,请重试')
  }
}
// 获取销售属性下拉方法
const baseSaleAttrList = ref<SaleAttrModel[]>([]) // 原始数据
const saleAttrList = computed(() => { // 根据表格中已有的数据进行计算
  // spuForm.value.spuSaleAttrList // 表格数据
  // baseSaleAttrList 下拉数据
  // 计算出一个新的下拉数据,新的下拉数据中是没有表格中的数据
  return baseSaleAttrList.value.filter(item => {
    // 判断当前下拉的数据是不是在表格中存在
    let isExist = spuForm.value.spuSaleAttrList?.some(attr => attr.baseSaleAttrId == item.id)
    // 如果存在,就过滤掉,不存在就保留
    return !isExist
  })
})
const getBaseSaleAttrList = async () => {
  try {
    let result = await spuApi.getBaseSaleAttrList()
    baseSaleAttrList.value = result
  } catch (error) {
    console.log(error)
    ElMessage.error('获取销售属性下拉失败,请重试')
  }
}

// 编辑获取图片列表数据
const getSpuImageListBySpuId = async () => {
  try {
    let result = await spuApi.getSpuImageListBySpuId(props.spuInfo.id!)
    // 组装数据,因为图片预览需要 name和url 两个属性

    spuImageList.value = result.map(item => {
      return {
        ...item,
        name: item.imgName,
        url: item.imgUrl
      }
    });
  } catch (error) {
    console.error(error)
    ElMessage.error('获取的图片列表数据失败,请重试')
  }
}
// 编辑获取销售属性数据
const getSpuSaleAttrListBySpuId = async () => {
  try {
    let result = await spuApi.getSpuSaleAttrListBySpuId(props.spuInfo.id!)
    spuForm.value.spuSaleAttrList = result
  } catch (error) {
    console.error(error)
    ElMessage.error('获取的销售属性数据失败,请重试')    
  }
}

// 页面初始化
onMounted(() => {
  // 判断是不是编辑
  if (props.spuInfo.id) {
    spuForm.value = cloneDeep(props.spuInfo) // 回显普通数据
    getSpuImageListBySpuId()
    getSpuSaleAttrListBySpuId()
  }
  getTrademarkList();
  getBaseSaleAttrList();
})


</script>

<style scoped>

</style>